package service

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"server/global"
	"server/model/other"
	"server/utils"
)

var (
	urlIP      = "https://restapi.amap.com/v3/ip"
	urlWeather = "https://restapi.amap.com/v3/weather/weatherInfo"
)

type GaodeService struct {
}

// GetLocationByIP 根据IP地址获取地理位置信息
func (g *GaodeService) GetLocationByIP(ip string) (other.IPResponse, error) {
	data := other.IPResponse{}
	req := other.IPRequest{
		Key: global.Config.Gaode.Key,
		IP:  ip,
	}
	method := "GET"
	params := map[string]string{
		"ip":  req.IP,
		"key": req.Key,
	}

	res, err := utils.HttpRequest(urlIP, method, nil, params, nil)
	if err != nil {
		return data, err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return data, fmt.Errorf("request failed with status code: %d", res.StatusCode)
	}

	byteData, err := io.ReadAll(res.Body)
	if err != nil {
		return data, err
	}
	if json.Unmarshal(byteData, &data) != nil {
		return data, err
	}
	return data, nil
}

// GetWeatherByAdcode 根据城市编码获取实时天气信息
func (g *GaodeService) GetWeatherByAdcode(adcode string) (other.Live, error) {
	data := other.WeatherResponse{}
	req := other.WeatherRequest{
		Key:  global.Config.Gaode.Key,
		City: adcode,
	}
	method := "GET"
	params := map[string]string{
		"city": req.City,
		"key":  req.Key,
	}
	res, err := utils.HttpRequest(urlWeather, method, nil, params, nil)
	if err != nil {
		return other.Live{}, err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return other.Live{}, fmt.Errorf("request failed with status code: %d", res.StatusCode)
	}

	byteData, err := io.ReadAll(res.Body)
	if err != nil {
		return other.Live{}, err
	}

	err = json.Unmarshal(byteData, &data)
	if err != nil {
		return other.Live{}, err
	}

	// 检查是否有返回的天气数据
	if len(data.Lives) == 0 {
		return other.Live{}, fmt.Errorf("no live weather data available") // 没有天气数据时返回错误
	}

	// 返回当天的天气数据
	return data.Lives[0], nil
}
